package VariablePicker;

import java.util.ArrayList;
import java.util.Collections;

public class SmallPicker extends VariablePicker {

	@Override
	public int pickVariable(ArrayList<int[]> clauses) {
		// find smallest clause
		int index = 0, temp, bound = Integer.MAX_VALUE;
		for(int i = 0; i < clauses.size(); i++) {
			temp = clauses.get(i).length;
			if(temp < bound) {
				bound = temp;
				index = i;
			}
		}
		
		// Put clauses into sorted list
		ArrayList<Integer> addList = new ArrayList<Integer>();
		
		for(int i = 0; i < clauses.size(); i++ ) {
			addList.addAll(toIntegerList(clauses.get(i)));
		}
		
		Collections.sort(addList);
		
		// Find the most occurring variable in small clause 
		bound = Integer.MIN_VALUE;
		int var = 0;
		int [] smallClause = clauses.get(index);
		for( int i = 0; i < smallClause.length; i++ ) {
			temp = getVariableCount(smallClause[i], addList);
			if(temp > bound) {
				bound = temp;
				var = smallClause[i];
			}
		}
		return var;
	}
	
	int getVariableCount(int var, ArrayList<Integer> variableList) {
		int count = 0;
		
		// Count positive instances
		int i,index = Collections.binarySearch(variableList, var);
		i = index;
		while(i < variableList.size() 
				&& variableList.get(i) == var) {
			count++; i++;
		}
		i = index-1;
		while(i >= 0 && variableList.get(i) == var) {
			count++; i--;
		}
		
		// Count negative instances
		index = Collections.binarySearch(variableList, -var);
		
		i = index;
		if(index >= 0) {
			while(i < variableList.size() 
					&& variableList.get(i) == -var) {
				count++; i++;
			}
			i = index-1;
			while(i >= 0 && variableList.get(i) == -var) {
				count++; i--;
			}
		}
		return count;
	}
	
	
	
}
